package com.rxjava;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.ReplaySubject;

public class ReplaySubjectDemo {

	public static void main(String[] args) {
		//ReplaySubject会发射所有数据给观察者，无论它们是何时订阅的。也有其它版本的ReplaySubject，在重放缓存增长到一定大小的时候或过了一段时间后会丢弃旧的数据。
		ReplaySubject<String>replaySubject = ReplaySubject.create(); //创建默认初始缓存容量大小为16的ReplaySubject，当数据条目超过16会重新分配内存空间，使用这种方式，不论ReplaySubject何时被订阅，Observer都能接收到数据
		//replaySubject = ReplaySubject.create(100);//创建指定初始缓存容量大小为100的ReplaySubject
		//replaySubject = ReplaySubject.createWithSize(2);//只缓存订阅前最后发送的2条数据
		 //replaySubject=ReplaySubject.createWithTime(1,TimeUnit.SECONDS,Schedulers.computation());  //replaySubject被订阅前的前1秒内发送的数据才能被接收
		replaySubject.onNext("replaySubject:pre1");
		replaySubject.onNext("replaySubject:pre2");
		replaySubject.onNext("replaySubject:pre3");
		replaySubject.subscribe(new Observer<String>() {

			@Override
			public void onSubscribe(Disposable disposable) {

			}

			@Override
			public void onError(Throwable throwable) {

			}

			@Override
			public void onComplete() {

			}

			@Override
			public void onNext(String s) {
				System.out.println("replaySubject observer1:" + s);
			}

		});
		replaySubject.onNext("replaySubject:after1");
		replaySubject.onNext("replaySubject:after2");
	}

}
